
//
//  SchollFriendManagerDetailViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/29.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "SchollFriendManagerDetailViewController.h"

#import "AddAnswerView.h"
#import "ChatTableViewCell.h"

static NSString * const kChatTableViewCellIdentifier = @"chatTableViewCellIdentifier";

@interface SchollFriendManagerDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIView * bottomBackView; // 下面魄背景
@property (nonatomic, strong) UIButton * backButton; // 返回按钮
@property (nonatomic, strong) UIButton * addAnswerButton; // 添加回复按钮
@property (nonatomic, strong) UITableView * chatTableView; // 聊天表格视图
@property (nonatomic, strong) AddAnswerView * addAnswerView; // 消息输入视图
@property (nonatomic, assign) NSInteger pageNum; // 页数
@property (nonatomic, assign) NSInteger pageSum; // 总页数
@property (nonatomic, strong) NSMutableArray * dataSource; // 数据源
@property (nonatomic, assign) CGFloat cellHeight; // cell 高度

@end

@implementation SchollFriendManagerDetailViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // 添加视图
    [self.view addSubview:self.nameLabel];
    [self.view addSubview:self.bottomBackView];
    [self.view addSubview:self.chatTableView];
    [_bottomBackView addSubview:self.backButton];
    [_bottomBackView addSubview:self.addAnswerButton];
    
    // 自动布局
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.805);
        make.height.equalTo(self.view).multipliedBy(0.06);
        make.top.offset(SCREEN_HEIGHT * 0.092);
        make.right.offset(0);
    }];
    [_bottomBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(_nameLabel);
        make.height.equalTo(_nameLabel).multipliedBy(1.2);
        make.bottom.offset(SCREEN_HEIGHT * -0.09);
        make.right.offset(0);
    }];
    [_chatTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nameLabel.mas_bottom);
        make.left.equalTo(_nameLabel);
        make.bottom.equalTo(_bottomBackView.mas_top);
        make.right.offset(0);
    }];
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(_bottomBackView).multipliedBy(0.65);
        make.width.equalTo(_backButton.mas_height).multipliedBy(2.84);
        make.centerY.equalTo(_bottomBackView);
        make.centerX.equalTo(_bottomBackView).multipliedBy(0.75);
    }];
    [_addAnswerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(_bottomBackView).multipliedBy(0.6);
        make.width.equalTo(_backButton).multipliedBy(1.2);
        make.centerY.equalTo(_backButton);
        make.centerX.equalTo(_bottomBackView).multipliedBy(1.25);
    }];
    
    // 下拉加载更多
    _chatTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNum += 1;
        if (_pageNum >= _pageSum) {
            [MBProgressHUD showError:@"没有更多数据"];
            [_chatTableView.mj_header endRefreshing];
            return ;
        }
        [self loadData];
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 首次加载数据
    _pageNum = 1;
    [self loadData];
}

#pragma mark 🌷🌷🌷UITableViewDataSource🌷🌷🌷
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kChatTableViewCellIdentifier forIndexPath:indexPath];
    
    // 单元格赋值
    cell.cellData = _dataSource[indexPath.row];
    
    _cellHeight = [cell getCellHeight];
    
    return cell;
}
#pragma mark 🌷🌷🌷UITableViewDelegate🌷🌷🌷
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _cellHeight;
}

#pragma mark 🌷🌷🌷envent responds🌷🌷🌷
- (void)respondsToBackButton {
    // 移除本视图与控制器
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}
- (void)respondsToAddAnswerButton {
    // 添加消息输入视图
    [self.view addSubview:self.addAnswerView];
    
    // 自动布局
    [_addAnswerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(self.view);
        make.center.equalTo(self.view);
    }];
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)loadData {
    // POST参数
    NSMutableDictionary * paramters = [NSMutableDictionary dictionary];
    [paramters setObject:_friendid forKey:@"friendId"];
    [paramters setObject:@(_pageNum) forKey:@"pageNum"];
    
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"加载中..." url:BASEURLAPPEND(PERSONALHOMEPAGE_SYSTEMMESSAGE_HISTORYLIST_URL) parameters:paramters finish:^(id responseObject, NSError *error) {
        if (!error) {
            if ([responseObject[@"status"] integerValue] == 1) {
                [MBProgressHUD showSuccess:@"加载完成！"];
                
                // 保存数据
                _pageSum = [responseObject[@"pageCount"] integerValue];
                NSDictionary * data = responseObject[@"data"];
                NSArray * list = data[@"list"];
                [list arrayByAddingObjectsFromArray:self.dataSource];
                [_dataSource removeAllObjects];
                [_dataSource addObjectsFromArray:list];
                
                // 刷新表格
                [_chatTableView reloadData];
            } else {
                [MBProgressHUD showSuccess:@"加载失败！"];
            }
        } else {
            [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
        }
        [_chatTableView.mj_header endRefreshing];
    }];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.textColor = RGB_COLOR(131, 131, 131, 1);
        _nameLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _nameLabel;
}
- (UIView *)bottomBackView {
    if (!_bottomBackView) {
        _bottomBackView = [[UIView alloc] init];
        _bottomBackView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomBackView;
}
- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"i_up_返回_03.png"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(respondsToBackButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}
- (UIButton *)addAnswerButton {
    if (!_addAnswerButton) {
        _addAnswerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _addAnswerButton.titleLabel.font = [UIFont systemFontOfSize:20];
        _addAnswerButton.layer.cornerRadius = 10;
        _addAnswerButton.layer.borderColor = RGB_COLOR(193, 193, 193, 1).CGColor;
        _addAnswerButton.layer.borderWidth = 1;
        [_addAnswerButton setTitle:@"添加回复" forState:UIControlStateNormal];
        [_addAnswerButton setTitleColor:RGB_COLOR(236, 162, 106, 1) forState:UIControlStateNormal];
        [_addAnswerButton addTarget:self action:@selector(respondsToAddAnswerButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addAnswerButton;
}
- (UITableView *)chatTableView {
    if (!_chatTableView) {
        _chatTableView = [[UITableView alloc] init];
        
        // 设置数据源
        _chatTableView.dataSource = self;
        // 设置代理
        _chatTableView.delegate = self;
        // 去除分隔线
        _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 预估高度
        _chatTableView.estimatedRowHeight = SCREEN_HEIGHT * 0.6;
        // 注册单元格
        [_chatTableView registerClass:[ChatTableViewCell class] forCellReuseIdentifier:kChatTableViewCellIdentifier];
    }
    return _chatTableView;
}
- (AddAnswerView *)addAnswerView {
    if (!_addAnswerView) {
        _addAnswerView = [[AddAnswerView alloc] initWithSendMessageBlock:^(NSString *message) {
            // POST参数
            NSMutableDictionary * paramters = [NSMutableDictionary dictionary];
            [paramters setObject:message forKey:@"content"];
            [paramters setObject:_friendid forKey:@"friendId"];
            
            [[NetTool sharedTool] requestMethod:POST loadingMsg:@"发送中..." url:BASEURLAPPEND(PERSONALHOMEPAGE_SYSTEMMESSAGE_SENDMSG_URL) parameters:paramters finish:^(id responseObject, NSError *error) {
                if (!error) {
                    if ([responseObject[@"status"] integerValue] == 1) {
                        [MBProgressHUD showSuccess:@"发送成功！"];
                        [self loadData];
                    } else {
                        [MBProgressHUD showSuccess:@"发送失败！"];
                    }
                } else {
                    [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
                }
            }];
        }];
    }
    return _addAnswerView;
}
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
